#!/user/bin/env python
# -*- coding: utf-8 -*-
from datetime import datetime, timedelta
from controls.data_topic_title_mysql import TopicTitleItem
from utils import log

from sqlalchemy.orm import mapper, sessionmaker
from sqlalchemy import Table, MetaData, Column, Integer, Unicode, UnicodeText, DateTime, desc
from sqlalchemy.sql.sqltypes import TIMESTAMP
from sqlalchemy.sql import func
from data_pool_mysql import engine

Session = sessionmaker()
Session.configure(bind=engine)

""" topic_like_item collection has
    id:             自增id
    topicid:        话题id（int）
    userid:         用户id（int）
    ctime:          like时间（datetime）
"""

metadata = MetaData()

class TopicLikeItem(object):
    """docstring for TopicLikeItem"""

    def to_dict(self):
        res = {}
        res['topicid'] = self.topicid
        res['userid'] = self.userid
        res['ctime'] = self.ctime
        return res

    def __repr__(self):
        return "%d" % (self.topicid)


topic_like_table = Table(
    'topic_like', metadata,
    Column('id', Integer, primary_key=True, autoincrement=True),
    Column('topicid', Integer, index=True, nullable=False),
    Column('userid', Integer, nullable=False),
    Column('ctime', TIMESTAMP, server_default=func.now())
)

mapper(TopicLikeItem, topic_like_table)


def create_topic_like_table_if_not_exist():
    metadata.create_all(engine)


def add_topic_like_item(p_item):
    item = TopicLikeItem()
    item.topicid = p_item['topicid']
    item.userid = p_item['userid']

    try:
        session = Session()
        session.add(item)
        session.flush()
        session.commit()
        return True
    except Exception as e:
        log.exp(e)
        session.rollback()
        return False
    finally:
        session.close()

def get_topic_like_by_userid(p_userid):
    try:
        session = Session()
        items = session.query(TopicLikeItem).filter_by(userid=p_userid).all()
        items_dict = [i.to_dict() for i in items]
        res = [i['topicid'] for i in items_dict]
        return res
    except Exception as e:
        log.exp(e)
        session.rollback()
        return None
    finally:
        session.close()


def get_topic_like_count_map_by_topicid_list(p_topicid_list):
    try:
        session = Session()
        items = session.query(TopicLikeItem.topicid, func.count(TopicLikeItem))\
            .filter(TopicLikeItem.topicid.in_(p_topicid_list))\
            .group_by(TopicLikeItem.topicid).all()
        topic_like_count_map = dict(items)
        return topic_like_count_map
    except Exception as e:
        log.exp(e)
        session.rollback()
        return None
    finally:
        session.close()

def get_topic_like_by_topicid_userid(p_topicid, p_userid):
    try:
        session = Session()
        item = session.query(TopicLikeItem).filter_by(topicid=p_topicid, userid=p_userid).first()
        if item:
            res = item.to_dict()
        else:
            res = None
        return res
    except Exception as e:
        log.exp(e)
        session.rollback()
        return None
    finally:
        session.close()

def get_topic_like_count_by_topicid(p_topicid):
    try:
        session = Session()
        item = session.query(TopicLikeItem.topicid, func.count(TopicLikeItem)) \
            .filter_by(topicid=p_topicid).group_by(TopicLikeItem.topicid).first()
        if item:
            return item[1]
        else:
            return None
    except Exception as e:
        log.exp(e)
        session.rollback()
        return None
    finally:
        session.close()


def del_topic_like_by_topicid_and_userid(p_topicid, p_userid):
    try:
        session = Session()
        session.query(TopicLikeItem).filter_by(topicid=p_topicid, userid=p_userid).delete()
        session.flush()
        session.commit()
        return True
    except Exception as e:
        log.exp(e)
        session.rollback()
        return None
    finally:
        session.close()


def get_all_topic_like():
    """
    在刷新脚本里使用，正式环境中尽量不要使用
    慎用！！！
    """
    try:
        session = Session()
        items = session.query(TopicLikeItem).all()
        return [i.to_dict() for i in items]
    except Exception as e:
        log.exp(e)
        session.rollback()
        return None
    finally:
        session.close()


if __name__ == '__main__':
    create_topic_like_table_if_not_exist()
    item = {
        'topicid': 1,
        'userid': 1
    }
    add_topic_like_item(item)